from django.db import models

# Create your models here.
from Final_Project.Tools import get_dict
from CarManage.models import Car
from PersonManage.models import Driver


class Station(models.Model):
    name = models.CharField(max_length=20, primary_key=True)

    def to_dict(self, fields=None, exclude=None):
        return get_dict(self, fields, exclude)


class Route(models.Model):
    RouteID = models.CharField(max_length=20, primary_key=True, blank=True)
    ManagerID = models.CharField(max_length=20, null=True, blank=True)
    State = models.CharField(max_length=6, default='正常运行', blank=True)
    RouteStopUseDate = models.DateField(null=True, blank=True)
    RouteStopUseReason = models.TextField(null=True, blank=True)
    steps = models.ManyToManyField(to=Station, blank=True)

    def to_dict(self, fields=None, exclude=None):
        ans = get_dict(self, fields, exclude)
        steps = []
        for st in self.steps.through.objects.filter(route=self.RouteID).order_by('id'):
            print(st.station.to_dict())
            steps.append(st.station.to_dict()["name"])
        ans['steps'] = steps
        return ans


class Rota(models.Model):
    Route = models.ForeignKey(to=Route, on_delete=models.CASCADE, blank=True)
    Car = models.ForeignKey(to=Car, on_delete=models.CASCADE, blank=True)
    Driver = models.ForeignKey(to=Driver, on_delete=models.CASCADE, blank=True)
    CarSendTime = models.TimeField(blank=True)
    Finished = models.BooleanField(default=False, blank=True)

    def to_dict(self, fields=None, exclude=None):
        return get_dict(self, fields, exclude)


class Service(models.Model):
    Route = models.ForeignKey(to=Route, on_delete=models.SET_NULL, blank=True, null=True)
    Car = models.ForeignKey(to=Car, on_delete=models.SET_NULL, blank=True, null=True)
    Driver = models.ForeignKey(to=Driver, on_delete=models.SET_NULL, blank=True, null=True)
    CarSendTime = models.TimeField(blank=True)
    CarSendDate = models.DateField(blank=True)
    Record = models.TextField(null=True, blank=True)

    def to_dict(self, fields=None, exclude=None):
        return get_dict(self, fields, exclude)
